from flask import Flask, render_template, request
from flask_socketio import SocketIO, send

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, cors_allowed_origins='*')


@app.route('/')
def index():
    return render_template('index.html')


@socketio.on('message')
def handle_message(data):
    ip_address = request.remote_addr  # 获取客户端 IP 地址
    message_with_ip = {'ip': ip_address, 'message': data}
    print(f'received message: {message_with_ip}')
    send(message_with_ip, broadcast=True)


if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', debug=True)
